/**
 * Created by cheny on 2016/1/26.
 */

var Cacheman = require('cacheman');
var accesstoken = require('./access_token.js');
var jsapiticket = require('./jsapi_ticket.js');
var jsapisign = require('./jsapi_sign.js');

var Wechat = function(args){

    var appId = args.appid;
    var appSecret = args.appsecret;
    var cachettl = args.cache_ttl || 7000;

    var cacheopts = {
        ttl:cachettl
    };

    if(args.cache_engine !== undefined && args.cache_engine == "redis")
    {
        cacheopts = {
            engine: 'redis',
            port: args.cache_port,
            host: args.cache_host,
            password:args.cache_password
        };
    }

    var self = {};
    var cache = new Cacheman(appId,cacheopts);

    self.getAccessToken = function(callback)
    {
        var _getToken = function(cb){
            accesstoken.getAccessToken(appId,appSecret,function(err,token){
                cb(err,token);
            });
        }
        cache.wrap('accesstoken',_getToken, cachettl,function (err, data) {
            callback(data);
        });
    },
    self.getJsApiTicket = function(callback)
    {
        self.getAccessToken(function(accesstoken){
            var _getTicket = function(cb)
            {
                jsapiticket.getTicket(accesstoken,function(err,ticket){
                    cb(err,ticket);
                })
            };
            cache.wrap('jsapiticket',_getTicket, cachettl,function (err, data) {
                callback(data);
            });
        })
    }
    self.getJsApiSignature = function(url,callback)
    {
        self.getJsApiTicket(function(ticket){

            var _getSign = function(cb)
            {
                var sign = jsapisign.getJsApiSign(ticket,url);
                sign.appid = appId;
                cb(null,sign);
            }

            var _cachekey = "urlsign"+url;
            cache.wrap(_cachekey,_getSign, cachettl,function (err, data) {
                callback(data);
            });
        });
    }
    return self;
}

module.exports = {
    create: function(args) {
        return Wechat(args);
    }
};
